<?php

class socialModel
{

    /**
     * 基类
     * @var object
     */
    private $base;

    /**
     * Mysql 连接
     * @var resources
     */
    private $db;

    /**
     * Redis 连接
     * @var resources
     */
    private $redis;

    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
    }



    //绑定类型
    static $bindTypes = array(
        2 => 'qq',
        3 => 'sina',
        4 => 'weixin',
        5 => 'renren',
        6 => 'phone'
    );

    /**
     * 绑定新浪用户
     * @param type $sinaData
     * @param type $uid
     */
    public function bindUser($openid, $access_token, $expire, $channel, $union_id=0, $bindInfo = array())
    {
        //渠道id
        if (!array_key_exists($channel, self::$bindTypes))
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        else
        {
            $socialType = self::$bindTypes["$channel"];
        }
        // 防止同一绑定请求连续发送
        if($this->redis->hget(REDIS_PREFIX.'bind', $channel.'_'.$openid))
        {
            // $_ENV['error']->getErrors(100);
            // exit;
        }
        $this->redis->hset(REDIS_PREFIX.'bind', $channel.'_'.$openid, 1);
        $isNewUser = 0; // 新绑定用户标识
        $union_id = $channel == 4 ? $union_id : 0;
        $time = time();
        $giveNewEnergy = 0; //是否是第一次绑定
        $cid = $this->base->cid;
        $fromChannel = $bindInfo['fromChannel'];
        $phone = isset($bindInfo['phone']) ? $bindInfo['phone'] : 0;
        $pwd = isset($bindInfo['pwd']) ? $bindInfo['pwd'] : '';
        $province = (isset($bindInfo['province']) && $bindInfo['province']) ? $bindInfo['province'] : '上海';
        $city = (isset($bindInfo['city']) && $bindInfo['city']) ? $bindInfo['city'] : '虹口区';
        unset($bindInfo['fromChannel'],$bindInfo['phone'],$bindInfo['pwd'],$bindInfo['province'],$bindInfo['city']);
        
        // 兼容安卓版本微信登录未传unionid的问题
        if($channel == 4 && !$union_id)
        {
            $weixinUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}";
            $weixinUserInfo = common::getContents($weixinUrl, array(), 5);
            $weixinUserInfo = $weixinUserInfo ? json_decode($weixinUserInfo, TRUE) : array();

            if(!empty($weixinUserInfo['unionid']))
            {
                $union_id = $weixinUserInfo['unionid'];
                $this->db->update("update r_social_user set union_id='{$weixinUserInfo['unionid']}' where channel='{$channel}' and openid='{$openid}' and union_id=''");
            }
        }

        $sid = NULL;

        if($channel == 4 && $union_id)
        {
            // 微信使用union_id识别唯一用户
            $sid = $this->db->getOne("select sid from r_social_user where union_id = '" . $union_id . "' and channel = '" . $channel. "'");
        }

        if(!$sid)
        {
            $sid = $this->db->getOne("select sid from r_social_user where openid = '" . $openid . "' and channel = '" . $channel. "'");
        }

        if( $sid > 0 && $channel == 6 ) $sid = $phone;
        $sid > 0 && $user = $this->db->getRowTable('r_user', array(), "$socialType={$sid}");
        $social_data = array(
            'channel' => $channel,
            'openid' => $openid,
            'access_token' => $access_token,
            'union_id' => $union_id,
            'expires' => $expire,
            'create_time' => $time,
            'last_time' => $time,
            'is_bind' => 1
        );
        $social_data = array_merge($social_data, $bindInfo);
        unset($social_data['height'],$social_data['weight'],$social_data['age'],$social_data['birthday']);
        $age = isset($bindInfo['age']) ? date("Y")-$bindInfo['age'] : '1981';
        $birthday = isset($bindInfo['birthday']) ? $bindInfo['birthday']:$age . '-01-01';
        if (!empty($this->base->token))
        {
            $uid = $this->base->uid;
            if ($sid)//验证社交id是否绑定
            {
                if (empty($user['uid'])) //解绑后再次绑定
                {
                    //不再更新用户昵称
                    unset($social_data['create_time'], $social_data['nickname']);
                    $this->base->db->updateRowTable("r_social_user", $social_data);
                    $updateInfo = array($socialType => $sid);
                    !empty($fromChannel) && $updateInfo['fromChannel'] = $fromChannel;
                    !empty($phone) && $updateInfo['phone'] = $phone;
                    !empty($pwd) && $updateInfo['pwd'] = $pwd;
                    $updateInfo['lastcid'] = $cid;
                    $_ENV['client']->setUserInfo($uid, $updateInfo);
                }
                elseif($user['uid'] == $uid)//重复绑定
                {
                    $this->redis->hdel(REDIS_PREFIX.'bind', $channel.'_'.$openid);
                    $_ENV['error']->getErrors(206);
                    exit;
                }
                else
                {
                    $this->redis->hdel(REDIS_PREFIX.'bind', $channel.'_'.$openid);
                    $_ENV['error']->getErrors(202);
                    exit;
                }
            }
            else //增加绑定
            {
                $insertStr = common::arrayToString($social_data);
                $sid = $this->base->db->insert("insert HIGH_PRIORITY into r_social_user set {$insertStr} on duplicate key update {$insertStr}");
                if ($sid)
                {
                    $updateInfo = array($socialType => $sid);
                    !empty($fromChannel) && $updateInfo['fromChannel'] = $fromChannel;
                    $updateInfo['lastcid'] = $cid;
                    !empty($phone) && $updateInfo['phone'] = $phone;
                    !empty($pwd) &&$updateInfo['pwd'] = $pwd;
                    $_ENV['client']->setUserInfo($uid, $updateInfo);
                }
                else
                {
                    $this->redis->hdel(REDIS_PREFIX.'bind', $channel.'_'.$openid);
                    $_ENV['error']->getErrors(100);
                    exit;
                }
            }
        }
        else //未登录用户
        {
            $header = $bindInfo['header'];
            unset($bindInfo['header']);
            $gender = isset($bindInfo['gender']) ? $bindInfo['gender'] : 2;
            //检查昵称是否重复
            $checkNickname = $this->base->checkNickname($bindInfo['nickname']);
            if($sid)
            {
                $uid = $user['uid'];
                unset($social_data['create_time'], $social_data['nickname']);
                $this->base->db->updateRowTable("r_social_user", $social_data);
                if(empty($uid)) //当作第一次绑定来处理
                {
                    $init_data = array(
                        'height' => 167,
                        'weight' => 66,
                        'age' => $age,
                        'birthday' => $birthday,
                        'level' => 1,
                        'gender' => $gender,
                        'total_mileage' => 0,
                        'total_elapsedtime' => 0,
                        "total_calorie" => 0,
                        'total_rate' => 0,
                        'max_mileage' => 0,
                        'max_elapsedtime' => 0,
                        'max_speed' => 0,
                        'max_five_time' => 0,
                        'max_ten_time' => 0,
                        'max_half_mtime' => 0,
                        'max_mara_time' => 0,
                        'total_energy' => 0,
                        'lights' => 0,
                        'occupation' => '',
                        'constellation' => '摩羯座',
                        'province' => $province,
                        'city' => $city,
                        'signature' => '跑步是一种运动，更是一种生活方式',
                        'background' => '',
                        'addtime' => time(),
                        'cid' => $cid,
                        'lastcid' => $cid,
                        'qq' => 0,
                        'sina' => 0,
                        'weixin' => 0,
                        'renren' => 0,
                        'fromChannel' => $fromChannel,
                        'is_defaultData' => 1  //注册使用的是默认身高体重等数据标记
                    );
                    !empty($phone) && $init_data['phone'] = $phone;
                    !empty($pwd) && $init_data['pwd'] = $pwd;
                    if($checkNickname == -3)//昵称重复
                    {
                        $bindInfo['nickname'] = $this->base->load('user')->makeNickname($bindInfo['nickname'].strtoupper(substr($socialType, 0,1)));
                    }
                    /*
                    elseif($checkNickname < 0)
                    {
                        $this->redis->hdel(REDIS_PREFIX.'bind', $channel.'_'.$openid);
                        $errorId = 500 - $checkNickname;
                        $_ENV['error']->getErrors($errorId);
                        exit;
                    }
                    */
                    // 用户头像及缩略图
                    $bindInfo['header_source'] = $this->base->load('qiniu')->saveNetImg($header);
                    $bindInfo['header'] = $this->base->load('qiniu')->qiniuPersist($bindInfo['header_source'], '?imageMogr2/thumbnail/180x180');
                    //插入新用户
                    if($channel == 6) $sid = $phone;
                    $data = array_merge($init_data, $bindInfo, array($socialType => $sid)); //合并绑定数据

                    isset($data['age']) && $data['age'] = $data['age'] <100 ? date("Y") - $data['age'] : 1996;
                    $uid = $this->base->load('user')->insert($data);
                    $_ENV['client']->setUserInfo($uid, $data);
                    $this->base->load('run')->runLevelUpRecord($uid, 1, 0, '欢迎您加入虎扑跑步，成长之路我们陪您一起鉴证!');
                    // 标记为已绑定游客
                    $this->base->db->update("update r_visitor set is_bind = 1 where cid = {$cid}");
                    //送正能量
                    if($this->base->vn >= 1400 || ($this->base->vn >= 1200 && $this->base->projectId == 2))
                    {
                        $giveNewEnergy = 1;
                    }
                    $isNewUser = 1;
                }
                else
                {
                    // $updateInfo = array_merge($bindInfo, array($socialType => $sid, 'uid'=> $uid));
                    // unset($updateInfo['nickname']);
                    $updateInfo = array($socialType => $sid);
                    !empty($fromChannel) && $updateInfo['fromChannel'] = $fromChannel;
                    !empty($phone) && $updateInfo['phone'] = $phone;
                    !empty($pwd) && $updateInfo['pwd'] = $pwd;
                    $_ENV['client']->setUserInfo($uid, $updateInfo);
                }
            }
            else //第一次绑定
            {
                $init_data = array(
                    'height' => 167,
                    'weight' => 66,
                    'age' => $age,
                    'birthday' => $birthday,
                    'level' => 1,
                    'gender' => $gender,
                    'total_mileage' => 0,
                    'total_elapsedtime' => 0,
                    "total_calorie" => 0,
                    'total_rate' => 0,
                    'max_mileage' => 0,
                    'max_elapsedtime' => 0,
                    'max_speed' => 0,
                    'max_five_time' => 0,
                    'max_ten_time' => 0,
                    'max_half_mtime' => 0,
                    'max_mara_time' => 0,
                    'total_energy' => 0,
                    'lights' => 0,
                    'occupation' => '',
                    'constellation' => '摩羯座',
                    'province' => $province,
                    'city' => $city,
                    'signature' => '跑步是一种运动，更是一种生活方式',
                    'background' => '',
                    'addtime' => time(),
                    'cid' => $cid,
                    'lastcid' => $cid,
                    'qq' => 0,
                    'sina' => 0,
                    'weixin' => 0,
                    'renren' => 0,
                    'fromChannel' => $fromChannel,
                    'is_defaultData' => 1  //注册使用的是默认身高体重等数据标记
                );
                !empty($phone) && $init_data['phone'] = $phone;
                !empty($pwd) && $init_data['pwd'] = $pwd;
                if($checkNickname == -3)//昵称重复
                {
                    $bindInfo['nickname'] = $this->base->load('user')->makeNickname($bindInfo['nickname'].strtoupper(substr($socialType, 0,1)));
                }
                /*
                elseif($checkNickname < 0)
                {
                    $this->redis->hdel(REDIS_PREFIX.'bind', $channel.'_'.$openid);
                    $errorId = 500 - $checkNickname;
                    $_ENV['error']->getErrors($errorId);
                    exit;
                }
                */
                // 用户头像及缩略图
                $bindInfo['header_source'] = $this->base->load('qiniu')->saveNetImg($header);
                $bindInfo['header'] = $this->base->load('qiniu')->qiniuPersist($bindInfo['header_source'], '?imageMogr2/thumbnail/180x180');
                //插入新用户
                $insertStr = common::arrayToString($social_data);//插入绑定数据
                $sid = $this->base->db->insert("insert HIGH_PRIORITY into r_social_user set {$insertStr} on duplicate key update {$insertStr}");
                if($channel == 6) $sid = $phone;
                $data = array_merge($init_data, $bindInfo, array($socialType => $sid)); //合并绑定数据
                $uid = $this->base->load('user')->insert($data);
                $_ENV['client']->setUserInfo($uid, $data);
                $this->base->load('run')->runLevelUpRecord($uid, 1, 0, '欢迎您加入虎扑跑步，成长之路我们陪您一起鉴证!');
                // 标记为已绑定游客
                $this->base->db->update("update r_visitor set is_bind = 1 where cid = {$cid}");
                //送正能量
                if($this->base->vn >= 1400 || ($this->base->vn >= 1200 && $this->base->projectId == 2))
                {
                    $giveNewEnergy = 1;
                }
                $isNewUser = 1;
            }
        }

        $old_uid = $this->base->db->getone("select old_uid from r_visitor where cid = '{$cid}'");
        if($old_uid > 1)
        {
            $this->base->db->query("update r_visitor set old_uid = 1, nickname = 'Runner' where cid = '{$cid}'");
        }
        $giveNewEnergy == 1 && $_ENV['client']->userEnergyChange($uid, 'new');
        $this->base->uid = $uid;
        $user_data = $_ENV['client']->getUserInfo($uid);
        $tokenStr = md5($uid . $time . $this->base->config['tokenStr']);
        $uid = $this->base->alphaId->getHash($uid);
        $tokenArr = array($uid, $time, $tokenStr, md5($this->base->client));
        $token = implode('-', $tokenArr);
        $user_data['token'] = $token;
        $user_data['isNewUser'] = $isNewUser;
        $this->redis->hdel(REDIS_PREFIX.'bind', $channel.'_'.$openid);
        return $user_data;
    }

    /**
     * 解除绑定社区用户
     * @param string $openid   社区绑定ID
     * @param string $type     社区名称
     */
    public function unBindUser($channel, $uid)
    {
        if (!array_key_exists($channel, self::$bindTypes))
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        else
        {
            $socialType = self::$bindTypes["$channel"];
        }
        if($channel == 6){
            $_ENV['error']->getErrors(207);
            exit();
        }
        $time = time();
        //已登录用户
        if ($this->base->uid)
        {
            $social_sid = $this->db->getOne("select $socialType from r_user where uid = '{$uid}'");
            if($social_sid == 0)
            {
                 $_ENV['error']->getErrors(205);
                exit();
            }
            else /*开始解除绑定*/
            {
                $other_bindTypes = self::$bindTypes;
                unset($other_bindTypes[$channel]);
                $sql_keyString = implode('+', array_values($other_bindTypes));
                $is_unique_social = $this->db->getOne("select $sql_keyString as social_sum from r_user where uid = '".$uid."'");
                if($is_unique_social == 0)
                {
                    $_ENV['error']->getErrors(204);
                    exit();
                }
                else
                {
                    /*删除r_user表中对应社区的绑定编号*/
                    $this->db->update("update r_user set $socialType = 0 where uid='" . $uid."'");
                    /*将r_social_user表中对应行 is_bind 标记为0（解除绑定状态）*/
                    $this->db->update("update r_social_user set is_bind = 0 where sid= '{$social_sid}'");

                    $user_data = $this->db->getRowTable('r_user', array(), "uid={$uid}");

                    $_ENV['client']->setUserInfo($uid, $user_data);

                    $tokenStr = md5($this->base->uid . $time . $this->base->config['tokenStr']);
                    $tokenArr = array($this->base->uid, $time, $tokenStr);
                    $token = implode('-', $tokenArr);
                    return $token;
                }

            }

        }
        else
        {
            $_ENV['error']->getErrors(302);
            exit();
        }
    }

    public function register($openid, $access_token, $expire, $channel, $union_id=0, $bindInfo = array(), $pubOpenid = NULL)
    {
        if (!array_key_exists($channel, self::$bindTypes))
        {
            return false;
        }
        else
        {
            $socialType = self::$bindTypes["$channel"];
        }
        $this->redis->hset(REDIS_PREFIX.'bind', $channel.'_'.$openid, 1);
        $union_id = $channel == 4 ? $union_id : 0;
        $time = time();
        $giveNewEnergy = 0; //是否是第一次绑定
        $fromChannel = $bindInfo['fromChannel'];
        $province = isset($bindInfo['province']) ? $bindInfo['province'] : '';
        $city = isset($bindInfo['city']) ? $bindInfo['city'] : '';
        unset($bindInfo['fromChannel'],$bindInfo['province'],$bindInfo['city']);

        // 兼容安卓版本微信登录未传unionid的问题
        if($channel == 4 && !$union_id)
        {
            $weixinUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}";
            $weixinUserInfo = common::getContents($weixinUrl, array(), 5);
            $weixinUserInfo = $weixinUserInfo ? json_decode($weixinUserInfo, TRUE) : array();

            if(!empty($weixinUserInfo['unionid']))
            {
                $this->db->update("update r_social_user set union_id='{$weixinUserInfo['unionid']}' where channel='{$channel}' and openid='{$openid}' and union_id=''");
            }
        }

        $sid = NULL;

        if($channel == 4 && $union_id)
        {
            // 微信使用union_id识别唯一用户
            $sid = $this->db->getOne("select sid from r_social_user where union_id = '" . $union_id . "' and channel = '" . $channel. "'");
        }

        if(!$sid)
        {
            $sid = $this->db->getOne("select sid from r_social_user where openid = '" . $openid . "' and channel = '" . $channel. "'");
        }

        // 更新微信公众号OPENID
        if($sid && $channel == 4 && $pubOpenid)
        {
            $this->db->update("update r_social_user set pub_openid='{$pubOpenid}' where sid='{$sid}' and pub_openid=''");
        }

        if($sid > 0){
            $userInfo = $this->db->getRowTable('r_user', array(), "$socialType={$sid}");
            $tokenStr = md5($userInfo['uid'] . $time . $this->base->config['tokenStr']);
            $uid = $this->base->alphaId->getHash($userInfo['uid']);
            $tokenArr = array($uid, $time, $tokenStr,md5($this->base->client));
            $token = implode('-', $tokenArr);
            $userInfo['token'] = $token;
            setcookie('joggers_u', $token, time() + 864000 * 365 * 10, '/', '.hupu.com', FALSE, TRUE);
            setcookie('joggers_u', $token, time() + 864000 * 365 * 10, '/', '.ijoggers.com', FALSE, TRUE);
            return $userInfo;
        }
        $social_data = array(
            'channel' => $channel,
            'openid' => $openid,
            'access_token' => $access_token,
            'union_id' => $union_id,
            'pub_openid' => $pubOpenid,
            'expires' => $expire,
            'create_time' => $time,
            'last_time' => $time,
            'is_bind' => 1
        );
        $social_data = array_merge($social_data, $bindInfo);
        unset($social_data['height'],$social_data['weight'],$social_data['age'],$social_data['birthday']);
        $age = isset($bindInfo['age']) ? date("Y")-$bindInfo['age'] : date("Y")-18;
        $birthday = isset($bindInfo['birthday']) ? $bindInfo['birthday']:$age.'-1-1';
        $header = $bindInfo['header'];
        unset($bindInfo['header']);
        //检查昵称是否重复
        $checkNickname = $this->base->checkNickname($bindInfo['nickname']);
        $gender = isset($bindInfo['gender']) ? $bindInfo['gender'] : 2;
        $init_data = array(
            'height' => 170,
            'weight' => 60,
            'age' => $age,
            'birthday' => $birthday,
            'level' => 1,
            'gender' => $gender,
            'total_mileage' => 0,
            'total_elapsedtime' => 0,
            "total_calorie" => 0,
            'total_rate' => 0,
            'max_mileage' => 0,
            'max_elapsedtime' => 0,
            'max_speed' => 0,
            'max_five_time' => 0,
            'max_ten_time' => 0,
            'max_half_mtime' => 0,
            'max_mara_time' => 0,
            'total_energy' => 0,
            'lights' => 0,
            'occupation' => '',
            'constellation' => '摩羯座',
            'province' => $province,
            'city' => $city,
            'signature' => '跑步是一种运动，更是一种生活方式',
            'background' => '',
            'addtime' => time(),
            'cid' => 0,
            'lastcid' => 0,
            'qq' => 0,
            'sina' => 0,
            'weixin' => 0,
            'renren' => 0,
            'fromChannel' => $fromChannel
        );
        if($checkNickname == -3)//昵称重复
        {
            $bindInfo['nickname'] = $this->base->load('user')->makeNickname($bindInfo['nickname'].strtoupper(substr($socialType, 0,1)));
        }
        // 用户头像及缩略图
        $bindInfo['header_source'] = $this->base->load('qiniu')->saveNetImg($header);
        $bindInfo['header'] = $this->base->load('qiniu')->qiniuPersist($bindInfo['header_source'], '?imageMogr2/thumbnail/180x180');
        //插入新用户
        $insertStr = common::arrayToString($social_data);//插入绑定数据
        $sid = $this->base->db->insert("insert HIGH_PRIORITY into r_social_user set {$insertStr} on duplicate key update {$insertStr}");
        $data = array_merge($init_data, $bindInfo, array($socialType => $sid)); //合并绑定数据
        $uid = $this->base->load('user')->insert($data);
        $this->base->load('client')->setUserInfo($uid, $data);
        $this->base->load('run')->runLevelUpRecord($uid, 1, 0, '欢迎您加入虎扑跑步，成长之路我们陪您一起鉴证!');
        //送正能量
        if($this->base->vn >= 1400 || ($this->base->vn >= 1200 && $this->base->projectId == 2))
        {
            $giveNewEnergy = 1;
        }

        $tokenStr = md5($uid . $time . $this->base->config['tokenStr']);
        $_uid = $this->base->alphaId->getHash($uid);
        $tokenArr = array($_uid, $time, $tokenStr,md5($this->base->client));
        $token = implode('-', $tokenArr);
        setcookie('joggers_u', $token, time() + 864000 * 365 * 10, '/', '.hupu.com', FALSE, TRUE);
        setcookie('joggers_u', $token, time() + 864000 * 365 * 10, '/', '.ijoggers.com', FALSE, TRUE);
        $giveNewEnergy == 1 && $this->base->load('client')->userEnergyChange($uid, 'new');
        $user_data = $this->base->load('client')->getUserInfo($uid);
        $user_data['token'] = $token;
        $this->redis->hdel(REDIS_PREFIX.'bind', $channel.'_'.$openid);
        return $user_data;
    }
}
